package org.openclinic.service.impl;

import java.util.List;

import org.openclinic.domain.MedicalSpecialty;
import org.openclinic.exception.DomainException;
import org.openclinic.exception.ErrorCodes;
import org.openclinic.repository.MedicalSpecialtyRepository;
import org.openclinic.service.MedicalSpecialtyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class MedicalSpecialtyServiceImpl implements MedicalSpecialtyService {
	
	@Autowired
	private MedicalSpecialtyRepository medicalSpecialtyRepository;
	
	@Override
	public void delete(long id) {
		medicalSpecialtyRepository.delete(id);
	}
	
	@Override
	public MedicalSpecialty find(long id) {
		return medicalSpecialtyRepository.findOne(id);
	}
	
	@Override
	public List<MedicalSpecialty> findAvailable() {
		return medicalSpecialtyRepository.findAvailable();
	}
	
	@Override
	public List<MedicalSpecialty> list() {
		return medicalSpecialtyRepository.findAll(new Sort("name"));
	}
	
	@Override
	public MedicalSpecialty save(MedicalSpecialty medicalSpecialty) {
		try {
			return medicalSpecialtyRepository.save(medicalSpecialty);
		} catch (DataIntegrityViolationException e) {
			throw new DomainException("medicalSpecialty", "name", ErrorCodes.UNIQUE_VIOLATED, medicalSpecialty.getName());
		}
	}
}
